package template

import (
	"lao-a/helper"
	"lao-a/models/h5"
	"lao-a/models/model"
)

type Component struct {
	model.TdComponentTemplate `xorm:"extends"`
	Motion                    string `xorm:"-"`
	Values                    []string
}

//GetTemplateByID 根据模板ID获取模板字典
func (m *DAO) GetComponentByPageID(pageID string) ([]Component, error) {
	var coms []Component
	sql := `SELECT  a.*
		FROM    td_component_template a
				INNER JOIN td_page_components b ON a.cmp_id = b.cmp_id
		WHERE   b.page_id = '` + pageID + `' order by b.sort_no`

	err := m.db.Sql(sql).Find(&coms)
	if err != nil {
		return nil, err
	}
	sql = "select * from td_component_values where cmp_id = ? order by sort_no"

	for inx, com := range coms {
		res, err := m.db.Collentions(sql, com.CmpId)
		if err != nil {
			return nil, helper.LogError("查询 组件ID:"+com.CmpId+" 元素值失败", err)
		}

		strRes := make([]string, 0)
		for _, r := range res {
			strRes = append(strRes, r["CmpValue"])
		}

		com.Values = strRes

		mtn := model.TaObjectMotions{}
		if _, err = m.db.Where("object_id=?", com.CmpId).
			And("object_type=?", h5.MOTION_COMPONENT).
			Get(&mtn); err != nil {
			return nil, helper.LogError("查询组件动效失败", err)
		}

		com.Motion = mtn.MotionConfig

		coms[inx] = com
	}
	return coms, nil
}
